package loggers;

import javax.microedition.lcdui.Image;
import javax.microedition.midlet.MIDletStateChangeException;

import util.PictureItem;
import video.MIDPPixelSource;
import video.VideoListener;
import connections.Uploader;

public class ImageLogger extends Logger implements VideoListener {

	MIDPPixelSource ps;

	PictureItem pictureItem;

	public void startApp() throws MIDletStateChangeException {

		super.startApp();
		//ps = new MIDPPixelSource(160, 120, null, pictureItem);
		ps = new MIDPPixelSource(160, 120);
		ps.addVideoListener(this, 30);
		setInputName("Camera");
	
	}
	
	public void displayInterface(){
		pictureItem = new PictureItem("Picture");
		pictureItem.setItemStateListener(this);
		mainForm.deleteAll();
		mainForm.append(pictureItem);
		mainForm.append(recordInfo);
		displayCurrentLog();
	}

	public void displayRecord(byte[] _bytes) {

		super.displayRecord(_bytes);

		try {
			pictureItem.setOverlay(Image.createImage(_bytes, 0, _bytes.length), 170);
			pictureItem.refresh();
		} catch (java.lang.IllegalArgumentException e) {
			System.out.println("Can't show picture");
		}

		 if (mainForm.size() < 2 || mainForm.get(1)!= pictureItem){

		     //mainForm.append(pictureItem);
		 }

	}

	public void requestData() {

		try {
			ps.grabFrame();
			byte[] imageArray = ps.getCompressedImageBytes();
			addALog(imageArray);
			displayCurrentLog();
		} catch (OutOfMemoryError e) {
			System.out.println("out of memory display");
		}

	}

	public void startLogging() {
		startIntervalometer();
		System.out.println("Started Intervalometer");
	}
	
	public void setUploaderProtocol(Uploader _uploader){
		_uploader.setPacketSize(-1);
		_uploader.setAllowBunching(false);
		_uploader.setContentFormattingStyle(Uploader.CONTENTS_RAW_BYTES);
		_uploader.setAppend(false);
		_uploader.setFilenameInsertionStyle(Uploader.INSERT_TIMESTAMP_IN_FILENAME);
	}

	public void stopLogging() {
		stopIntervalometer();

	}

	public void newFrame() {

		ps.grabFrame();
		pictureItem.setPicture(ps.getImage());
		pictureItem.refresh();
	}

}
